<?php

namespace App\Console\Commands\Shop;

use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Model\OrderSplitModel;
use App\Kuafu\Shop\Model\ShopDistributionBillRecordModel;
use App\Kuafu\WaiMai\Exceptions\WaiMaiException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ShopDistributionBillRecordDaily extends Command
{
    protected $signature = 'shop:distributionBillRecordDaily {date?} {shopId?}';

    protected $description = '店铺分销分佣记录';

    /**
     * @throws WaiMaiException
     */
    public function handle()
    {
        $date      = $this->argument('date') ?? date("Y-m-d", strtotime("-1 day"));
        $argShopId = $this->argument('shopId') ?? 0;
        $startTime = strtotime($date);
        $endTime   = strtotime($date) + 86399;
        $time      = time();
        try {

            for ($i = 0; $i <= 99; $i++) {
                if ($argShopId && $argShopId % 100 != $i) {
                    continue;
                }
                $list = [];
                OrderSplitModel::suffix($i)
                               ->where('orderStatus', CodeEnum::ORDER_STATUS_FINISHED)
                               ->where('refundStatus', '<>', CodeEnum::ORDER_REFUND_STATUS_ALL)
                               ->whereIn("sourceType", [CodeEnum::SOURCE_TYPE_MINI])
                               ->when($startTime && $endTime, function ($query) use ($endTime, $startTime) {
                                   $query->whereBetween('createdAt', [$startTime, $endTime]);
                               })
                               ->when($argShopId, function ($query) use ($argShopId) {
                                   $query->where('shopId', $argShopId);
                               })
                               ->where('distributionId', '>', 0)
                               ->chunk(500, function ($item) use ($time, $startTime, &$list) {
                                   foreach ($item as $v) {
                                       if (!($v->shopId && $v->distributionId)) {
                                           continue;
                                       }
                                       $k = $v->shopId . '-' . $v->distributionId;
                                       if (isset($list[$k])) {
                                           $list[$k]['amount']    += $v->realPayPrice;
                                           $list[$k]['brokerage'] += $v->distributionAmount;
                                           continue;
                                       }
                                       $list[$k] = [
                                           'shopId'              => $v->shopId,
                                           'distributionId'      => $v->distributionId,
                                           'amount'              => $v->realPayPrice,
                                           'brokerage'           => $v->distributionAmount,
                                           'settlementCycleTime' => $startTime,
                                           'createdAt'           => $time,
                                       ];
                                   }
                               });

                if ($list) {
                    foreach ($list as $v) {
                        $m = ShopDistributionBillRecordModel::query()->firstOrCreate([
                            'shopId'              => $v['shopId'],
                            'distributionId'      => $v['distributionId'],
                            'settlementCycleTime' => $v['settlementCycleTime'],
                        ]);

                        $m->amount    = $v['amount'];
                        $m->brokerage = $v['brokerage'];
                        $m->createdAt = $time;
                        $m->save();
                    }
//                    ShopDistributionBillRecordModel::batchAddData($list);
                }
                $this->info('OrderSplitModel Finish : ' . $i . ' count:' . count($list));
            }
        } catch (\Exception $e) {
            Log::info('distributionBillRecordDaily Err:', [
                'msg'       => $e->getMessage(),
                'date'      => $date,
                'argShopId' => $argShopId,
                'startTime' => $startTime,
                'endTime'   => $endTime,
            ]);
        }

    }
}
